<template>
    <div class="edit-popup">
        <popup ref="popupRef" title="分配应用权益" :async="true" width="550px" @confirm="handleSubmit" @close="handleClose">
            <el-form class="ls-form" ref="formRef" :rules="rules" :model="formData" label-width="60px">
                <el-scrollbar class="h-[400px] sm:h-[600px]">
                    <el-form-item label="应用" prop="app_id">
                        <div>
                            <el-checkbox label="全选/不全选" @change="handleSelectAll" />
                            <div>
                                <el-tree 
                                    ref="treeRef"
                                    :data="menuTree" 
                                    :props="{
                                        label: 'name',
                                        children: 'plugs',
                                    }"
                                    :check-strictly="true"
                                    node-key="app"
                                    :default-expand-all="true"
                                    :default-checked-keys="defaultCheckedKeys"
                                    show-checkbox />
                            </div>
                        </div>
                    </el-form-item>
                </el-scrollbar>
            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup>
import type { CheckboxValueType, ElTree, FormInstance } from "element-plus";
import { updateUserApp } from "@/api/cloudupdate";
import Popup from "@/components/popup/index.vue";

const emit = defineEmits(["success", "close"]);
const treeRef = shallowRef<InstanceType<typeof ElTree>>();
const formRef = shallowRef<FormInstance>();
const popupRef = shallowRef<InstanceType<typeof Popup>>();
const menuTree = ref<any[]>([]);
const defaultCheckedKeys = ref<any[]>([]);
const formData = reactive({
    id: "",
    app_id: [] as any[],
});

const rules = {
    name: [
        {
            required: true,
            message: "请输入名称",
            trigger: ["blur"],
        },
    ],
};

// 获取所有选择的节点包括半选中节点
const getDeptAllCheckedKeys = () => {
    const checkedKeys = treeRef.value?.getCheckedNodes();
    const halfCheckedKeys = treeRef.value?.getHalfCheckedNodes()!;
    checkedKeys?.unshift.apply(checkedKeys, halfCheckedKeys);
    return checkedKeys;
};

const allTreeArr = ref<any[]>([]);

// 递归获取所有节点的 key（使用 plugs 作为子节点属性）
const getAllTreeKey = (arr: any[]) => {
    arr.forEach((item: any) => {
        if (item?.app) {
            allTreeArr.value.push(item.app);
        }
        if (item?.plugs && item.plugs.length > 0) {
            getAllTreeKey(item.plugs);
        }
    });
};

// 全选/不全选操作
const handleSelectAll = (check: CheckboxValueType) => {
    if (check) {
        // 使用预先收集的所有 app key 全选
        treeRef.value?.setCheckedKeys(allTreeArr.value);
    } else {
        treeRef.value?.setCheckedKeys([]);
    }
};

const handleSubmit = async () => {
    await formRef.value?.validate();
    let params: any = [];
    formData.app_id = getDeptAllCheckedKeys()!;
    params = formData.app_id.map((item) => {
        return {
            user_id: formData.id,
            app_id: item.id,
            app_name: item.name,
            app: item.app,
        };
    });
    await updateUserApp({ userApp: params, user_id: formData.id });
    popupRef.value?.close();
    emit("success");
};

const handleClose = () => {
    emit("close");
};

const open = () => {
    popupRef.value?.open();
};

// 设置表单数据，初始化时获取所有节点 key
const setFormData = async (row: any, payedAppList: any) => {
    menuTree.value = payedAppList;
    // 获取所有节点的key并存入allTreeArr
    allTreeArr.value = []; // 先清空
    getAllTreeKey(menuTree.value);
    defaultCheckedKeys.value = row.userApp.map((item: any) => item.app);
    formData.id = row.id;
};

onMounted(() => {});

defineExpose({
    open,
    setFormData,
});
</script>
